using AutoMapper;
using MediatR;
using Work.API.Applications.Write.Commands;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Write.CommandHandlers
{
    /// <summary>
    /// 新增预约挂号处理器
    /// </summary>
    public class CreateAppointmentCommandHandler : IRequestHandler<CreateAppointmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Appintment> _repo;
        private readonly IBaseRepository<Patient> _patientRepo;
        private readonly IMapper _mapper;

        public CreateAppointmentCommandHandler(IBaseRepository<Appintment> repo, IBaseRepository<Patient> patientRepo, IMapper mapper)
        {
            _repo = repo;
            _patientRepo = patientRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(CreateAppointmentCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var patient = await _patientRepo.GetById(request.PatientId);
            if (patient == null || string.IsNullOrWhiteSpace(patient.CardNumber))
            {
                result.Code = ApiEnum.失败;
                result.Message = "请先办理就诊卡";
                result.Data = 0;
                return result;
            }

            var entity = _mapper.Map<Appintment>(request);
            entity.CardNumber = patient.CardNumber;
            entity.RegistrationNum = DateTime.Now.ToString("yyyyMMddHHmmss");

            var rows = await _repo.AddAsync(entity);
            if (rows > 0)
            {
                result.Code = ApiEnum.成功;
                result.Message = ApiEnum.成功.ToString();
                result.Data = rows;
            }
            else
            {
                result.Code = ApiEnum.失败;
                result.Message = ApiEnum.失败.ToString();
                result.Data = rows;
            }
            return result;
        }
    }
}











